import {
  createReducer,
  createAction,
  PayloadAction,
} from '@reduxjs/toolkit'

interface Todo {
  text: string;
  index: number;
  completed:boolean;
}

const addTodo = createAction<Todo>('ADD_TODO')
const toggleTodo = createAction<Todo>('TOGGLE_TODO')
const removeTodo = createAction<Todo>('REMOVE_TODO')

export const todosReducer = createReducer([] as Todo[], (builder) => {
  builder
    .addCase(addTodo, (state, action:PayloadAction<Todo>) => {
      // "mutate" the array by calling push()
      state.push(action.payload)
    })
    .addCase(toggleTodo, (state, action:PayloadAction<Todo>) => {
      const todo = state[action.payload.index]
      // "mutate" the object by overwriting a field
      todo.completed = !todo.completed
    })
    .addCase(removeTodo, (state, action:PayloadAction<Todo>) => {
      // Can still return an immutably-updated value if we want to
      return state.filter((todo, i) => i !== action.payload.index)
    })
})